﻿//+-------------------------------------------------------------------------------------------------------------------------------------------------------
//
//Description: NewFileWindow
//Author: Aravind Ramarathinam (aravr@microsoft.com)
//
//Copyright © Microsoft Corporation
//Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
//You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
//
//THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, 
//INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 
//See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
// 
//--------------------------------------------------------------------------------------------------------------------------------------------------------



using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using VmroleAuthor.Helpers;
using VmroleAuthor.ViewModels;
using Application = System.Windows.Application;
using MessageBox = System.Windows.MessageBox;
using UserControl = System.Windows.Controls.UserControl;

namespace VmroleAuthor.Views
{
    /// <summary>
    /// Interaction logic for NewFileWindow.xaml
    /// </summary>
    public partial class NewFileWindow : UserControl
    {
        public NewFileWindow()
        {
            InitializeComponent();
        }

        public const string NewFileWindowName = "NewFileWindow";   

        public string WindowTitle { get; set; }
        public CloudServiceManagerFileType CloudServiceManagerFileType { get; set; }

        public string FileToSavePath { get; private set; }
        public bool DataValid { get; private set; }        
        public string JsonFileNameInsidePackage { get; private set; }
        public string ViewDefFileName { get; private set; }  // only valid if it is resdef
        

        private void BrowseFolder(object sender, RoutedEventArgs e)
        {
            using (FolderBrowserDialog dlg = new FolderBrowserDialog())
            {
                dlg.Description = "Select Folder  " + this.WindowTitle;
                dlg.ShowNewFolderButton = true;               
                DialogResult result = dlg.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    FolderLocation.Text = dlg.SelectedPath;                   
                }
            }
        }

        private void OkButton_Click(object sender, RoutedEventArgs e)
        {
            if (!System.IO.Directory.Exists(FolderLocation.Text))
            {
                MessageBox.Show("Selected dir does not exist: " + FolderLocation.Text, DefinitionViewModel.ToolHeader);
                return;
            }  
            if (string.IsNullOrEmpty(this.FileName.Text))
            {
                MessageBox.Show("Name needs to be provided", DefinitionViewModel.ToolHeader);
                return;
            }

            try
            {
                 //validate ext
                string error = this.ValidateExt();
                if (!string.IsNullOrEmpty(error))
                {
                    MessageBox.Show(error, DefinitionViewModel.ToolHeader);
                    return; 
                }
                this.UpdateAndGetWorkingDir();
                if (System.IO.Directory.Exists(WorkingDir.Text))
                {
                    System.IO.Directory.Delete(WorkingDir.Text, true);                           
                }
                System.IO.Directory.CreateDirectory(WorkingDir.Text);                       
                this.UpdateAndGetJsonFileInPackage();
                this.UpdateAndGetFileToSavePath();

                this.DataValid = true;
                Window win = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.Name == NewFileWindowName);
                if (win != null) win.Close();   
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, DefinitionViewModel.ToolHeader);                            
            }          
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DataValid = false;
            Window win = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.Name == NewFileWindowName);
            if (win != null) win.Close();           
        }

        private void NameChanged(object sender, TextChangedEventArgs e)
        {
            if (!System.IO.Directory.Exists(FolderLocation.Text))
            {                             
                return;
            }           
            try
            {
                this.UpdateAndGetWorkingDir();
            }
            catch (ArgumentException)
            {                             
            }
        }

        private void FolderChanged(object sender, TextChangedEventArgs e)
        {
            if (!System.IO.Directory.Exists(FolderLocation.Text))
            {
                return;
            }
            try
            {
                this.UpdateAndGetWorkingDir();
            }
            catch (ArgumentException)
            {
            }           
        }

        private void UpdateAndGetWorkingDir()
        {
            string nameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(this.FileName.Text);          
            if (!string.IsNullOrEmpty(nameWithoutExt))
            {
                string suffix = DateTime.Now.ToString("MM-dd-yyyy-HH-mm-ss").ToString(CultureInfo.InvariantCulture);
                //suffix = suffix.Replace(':', '_');
                string dirname = string.Concat(nameWithoutExt, "-", suffix);
                this.WorkingDir.Text = System.IO.Path.Combine(FolderLocation.Text, dirname);               
            }           
        }

        private void UpdateAndGetJsonFileInPackage()
        {
            switch (this.CloudServiceManagerFileType)
            {
                case CloudServiceManagerFileType.ResourceExtensionPackage:
                    this.JsonFileNameInsidePackage = System.IO.Path.Combine(this.WorkingDir.Text, System.IO.Path.GetFileNameWithoutExtension(this.FileName.Text) + PackagingFormatHelper.ResExt);
                    break;
                case CloudServiceManagerFileType.ResourceDefinitionPackage:
                    this.JsonFileNameInsidePackage = System.IO.Path.Combine(this.WorkingDir.Text, System.IO.Path.GetFileNameWithoutExtension(this.FileName.Text) + PackagingFormatHelper.ResDef);
                    this.ViewDefFileName = System.IO.Path.Combine(this.WorkingDir.Text, System.IO.Path.GetFileNameWithoutExtension(this.FileName.Text) + PackagingFormatHelper.ViewDef); 
                    break;
            }            
        }

        private void UpdateAndGetFileToSavePath()
        {
            string nameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(this.FileName.Text);        
            switch (this.CloudServiceManagerFileType)
            {
                case CloudServiceManagerFileType.ResourceExtensionPackage:
                    this.FileToSavePath = System.IO.Path.Combine(FolderLocation.Text, nameWithoutExt + PackagingFormatHelper.ResExtPkg);
                    break;
                case CloudServiceManagerFileType.ResourceDefinitionPackage:
                    this.FileToSavePath = System.IO.Path.Combine(FolderLocation.Text, nameWithoutExt + PackagingFormatHelper.ResDefPkg);
                    break;
                case CloudServiceManagerFileType.ResourceDefinition:
                    this.FileToSavePath = System.IO.Path.Combine(FolderLocation.Text, nameWithoutExt + PackagingFormatHelper.ResDef);
                    break;
            }            
        }

        private string ValidateExt()
        {
            string error = null;
            string ext = System.IO.Path.GetExtension(this.FileName.Text);
            if (!string.IsNullOrEmpty(ext))
            {
                switch (this.CloudServiceManagerFileType)
                {
                    case CloudServiceManagerFileType.ResourceExtensionPackage:
                        if (!string.Equals(ext, PackagingFormatHelper.ResExtPkg, StringComparison.OrdinalIgnoreCase))
                        {
                            error = "Unrecognized file extension for resource extension package:" + ext;
                        }                        
                        break;
                    case CloudServiceManagerFileType.ResourceDefinitionPackage:
                        if (!string.Equals(ext, PackagingFormatHelper.ResDefPkg, StringComparison.OrdinalIgnoreCase))
                        {
                            error = "Unrecognized file extension for resource definition package :" + ext;
                        }                        
                        break;
                    case CloudServiceManagerFileType.ResourceDefinition:
                        if (!string.Equals(ext, PackagingFormatHelper.ResDef, StringComparison.OrdinalIgnoreCase))
                        {
                            error = "Unrecognized file extension for resource definition :" + ext;
                        }                        
                        break;                                          
                }
            }
            return error;
        }

       
    }
}
